/**
 * @file 分享
 */
(function() {

    function SwitchButton(elem, options){
        var elemOpt = elem.getAttribute('data-options');
        if(elemOpt){
            options = $.extend(options, $.parseJSON(elemOpt.replace(/'/g,'"')))
        }
        this.options = options;
        addHtml.call(this,elem,options);
    }
    SwitchButton.prototype.changeState = function(value) {
        var inputElem = $('input',this.elem);
        if(value){
            if(inputElem.val() === value){
                return;
            }else{
                changeState(this.elem,this.options)
            }
        }else{
            changeState(this.elem,this.options)
        }
        
    };
    function addHtml(elem,opts) {
        var htmlStr = '<div class="button-switch"><span class="button-slider"></span><input type="hidden" name="'+ opts.name +'" value="'+ opts.value +'" /></div>';
        var dd = $(htmlStr).appendTo(elem);

        this.elem = dd;
        // var input = $('input[name="'+ opts.name +'"]',dd);

        if(opts.value == opts.values[1]){
            dd.addClass("button-switch-off");
            $('.button-slider',dd).css({left:'1px'})
        }else{
        	dd.removeClass("button-switch-on");
        }
        bindEvent(dd,opts);
    }

    function bindEvent(elem,opt) {
    	elem.on("click",function() {
    		 changeState(elem,opt);
    	});
    }
    function changeState(elem,opt){
        var input = $("input",elem),
             that = elem;
         if(input.attr('isClick') == 1){
            return;
         }
         input.attr('isClick','1');
         if(input.val() == opt.values[0]){
            $(".button-slider",elem).animate({
                left:'1px'
            },200,'ease-in',function(){});
            setTimeout(function(){
                $(that).removeClass('button-switch-on').addClass("button-switch-off");
                input.val(opt.values[1]);
                input.attr('isClick','2');
            },200);
         }else{
            $(".button-slider",elem).animate({
                left:'25px'
            },200,'ease-in',function(){});
            setTimeout(function(){
                $(that).removeClass("button-switch-off").addClass('button-switch-on');
                input.val(opt.values[0]);
                input.attr('isClick','2');
            },200);
         }
         opt.clickFn && opt.clickFn(input,input.val());
    }
    $.fn.switchButton = function (options) {
        options = $.extend({
            values: [true, false],
            value: true,
        }, options);
        var objs = [];
        this.each(function (i, elem) {
            objs.push(new SwitchButton(elem, $.extend({}, options)))
        });
        return objs;
    };
})();
